package com.deer.wms.inventory.web;

import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.*;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.model.stockTake.*;
import com.deer.wms.inventory.service.*;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.model.BillRecordTypeConstants;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.service.ValidatorService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.deer.wms.project.root.util.FunctionUtil.nvl;

/**
* Created by ll on 2020/02/13.
*/
@RestController
@RequestMapping("/inventory/adjusts")
public class InventoryAdjustController {

    @Autowired
    private InventoryAdjustService inventoryAdjustService;
    @Autowired
    private ReasonService reasonService;
    @Autowired
    private ValidatorService validatorService;
    @Autowired
    private StockTakeMasterService stockTakeMasterService;
    @Autowired
    private StockTakeTaskService stockTakeTaskService;
    @Autowired
    private InventoryTransactService inventoryTransactService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private BillRecordService billRecordService;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private InventoryAdjustDetailService inventoryAdjustDetailService;

    @PostMapping("/insert")
    public Result add(@RequestBody InventoryAdjust inventoryAdjust) {
        inventoryAdjustService.save(inventoryAdjust);
        return ResultGenerator.genSuccessResult();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        inventoryAdjustService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping("/update")
    public Result update(@RequestBody InventoryAdjust inventoryAdjust) {
        inventoryAdjustService.updateById(inventoryAdjust);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        InventoryAdjust inventoryAdjust = inventoryAdjustService.getById(id);
        return ResultGenerator.genSuccessResult(inventoryAdjust);
    }

    @GetMapping("/list")
    public Result list(InventoryAdjustCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<InventoryAdjustDto> list = inventoryAdjustService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/deleteDetailAndMaster")
    public Result deleteDetailAndMaster(Integer id) {
        inventoryAdjustService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "创建库存调整单", notes = "创建库存调整单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/createInventoryAdjust")
    @Transactional
    public Result createInventoryAdjust(@RequestBody InventoryAdjustCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        List<Reason> reasons = reasonService.findList(new ReasonCriteria(criteria.getReason()));
        if (reasons.size() <= 0) {
            reasonService.save(new Reason(criteria.getReason()));
        }
        String tableName = "inventory_adjust";
        Integer nextId = validatorService.getNextId(tableName);
        String billNo = "IA"+"-"+nextId;
        Integer caseState =2;
        //添加调整单跟踪信息
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(36);//调整新增
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.save(billRecord);
        caseState = caseMasterService.createCase(billNo, 6, currentUser.getUserId(), criteria.getWareId(),criteria.getOrganizationId());
        InventoryAdjust inventoryAdjust = new InventoryAdjust(billNo,criteria.getOrganizationId(),criteria.getOrganizationName(),
                DateUtils.getNowDateTimeString(),criteria.getReason(),
                criteria.getReasonDescription(),criteria.getWareId(),criteria.getWareCode(),criteria.getWareName(),
                currentUser.getUserId(),criteria.getMemo(),currentUser.getUserName(),criteria.getInsertType());

        //BillRecord billRecord = new BillRecord(billNo,DateUtils.getNowDateTimeString(), currentUser.getUserId(),currentUser.getUserName());
        BillRecord billRecord1 =new BillRecord();
        billRecord1.setBillNo(billNo);
        billRecord1.setRecordType(37);//调整审核
        billRecord1.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord1.setCreateUserId(currentUser.getUserId());
        billRecord1.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord1,currentUser);
        if(caseState==1){
            billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord1.setModifyUserId(currentUser.getUserId());
            billRecord1.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord1);
        }
        if(criteria.getType().equals(1)) {
            if(criteria.getInsertType().equals(-2)){
                //billRecord.setRecordType(BillRecordTypeConstants.INVENTORY_CHECK_CREATE_INVENTORY_ADJUST_DRAFT);
                billRecord.setMemo("通过盘点单创建库存调整单草稿");
            }else{
                //billRecord.setRecordType(BillRecordTypeConstants.INVENTORY_CHECK_CREATE_INVENTORY_ADJUST);
                billRecord.setMemo("通过盘点单创建库存调整单");
                inventoryAdjust.setCaseState(caseState);
            }
            inventoryAdjust.setType(1);
            inventoryAdjust.setStockTakeMasterId(criteria.getStockTakeMasterId());
            StockTakeMaster stockTakeMaster = stockTakeMasterService.findList(new StockTakeMasterCriteria(criteria.getStockTakeMasterId())).get(0);
            stockTakeMaster.setState(6);
            stockTakeMasterService.updateById(stockTakeMaster);
            List<StockTakeTaskDto> stockTakeTaskDtos = stockTakeTaskService.findList(new StockTakeTaskCriteria(criteria.getStockTakeMasterId()));
            for(int i=0; i<stockTakeTaskDtos.size(); i++){
                StockTakeTaskDto  stockTakeTaskDto = stockTakeTaskDtos.get(i);
                if (!Objects.equals(stockTakeTaskDto.getState(), 2) || !Objects.equals(nvl(stockTakeTaskDto.getDifferQuantity()), 0.0d)
                    || !Objects.equals(stockTakeTaskDto.getType(), 21)) {
                    continue;
                }
                InventoryAdjustDetail inventoryAdjustDetail = new InventoryAdjustDetail(billNo,billNo+"-"+(i+1),
                        stockTakeTaskDto.getInventoryId(),stockTakeTaskDto.getItemCode(),stockTakeTaskDto.getItemName(),
                        stockTakeTaskDto.getBatchId(),stockTakeTaskDto.getBatchName(),stockTakeTaskDto.getCellCode(),
                        stockTakeTaskDto.getBoxCode(),stockTakeTaskDto.getPackDetailId(),stockTakeTaskDto.getPackDescribe(),
                        stockTakeTaskDto.getLpn(),stockTakeTaskDto.getDifferQuantity(),stockTakeTaskDto.getTaskQuantity(),
                        1,DateUtils.getNowDateTimeString(),currentUser.getUserId(),currentUser.getUserName(),criteria.getMemo());
                inventoryAdjustDetailService.save(inventoryAdjustDetail);
            }
        }
        else{
            inventoryAdjust.setType(2);
            if(criteria.getInsertType().equals(-2)){
                BillRecord billRecord3 =new BillRecord();
                billRecord3.setBillNo(billNo);
                billRecord3.setRecordType(43);//调整单草稿
                billRecord3.setCreateTime(DateUtils.getNowDateTimeString());
                billRecord3.setCreateUserId(currentUser.getUserId());
                billRecord3.setCreateUserName(currentUser.getUserName());
                billRecordService.save(billRecord3);
                //billRecord.setRecordType(BillRecordTypeConstants.MANUAL_CREATE_INVENTORY_ADJUST_DRAFT);
                billRecord.setMemo("手动选择库存创建库存调整单草稿");
            }else{
                //billRecord.setRecordType(BillRecordTypeConstants.MANUAL_CREATE_INVENTORY_ADJUST);
                billRecord.setMemo("手动选择库存创建库存调整单");
                inventoryAdjust.setCaseState(caseState);
            }
            for(int j=0;j<criteria.getAdjustDetails().size();j++){
                InventoryAdjustDetail inventoryAdjustDetail = criteria.getAdjustDetails().get(j);
                inventoryAdjustDetail.setBillNo(billNo);
                inventoryAdjustDetail.setDetailNo(billNo+"-"+(j+1));
                inventoryAdjustDetail.setDifferQuantity(inventoryAdjustDetail.getAdjustQuantity()-inventoryAdjustDetail.getQuantity());
                inventoryAdjustDetail.setState(1);
                inventoryAdjustDetail.setCreateTime(DateUtils.getNowDateTimeString());
                inventoryAdjustDetail.setCreateUseId(currentUser.getUserId());
                inventoryAdjustDetail.setCreateUseName(currentUser.getUserName());
                inventoryAdjustDetail.setMemo(criteria.getMemo());
                inventoryAdjustDetailService.save(inventoryAdjustDetail);
            }
        }

        inventoryAdjustService.save(inventoryAdjust);
        BillRecord billRecord2 =billRecordService.findByBillNoAndType(billNo,36);//调整新增
        billRecord2.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord2.setModifyUserId(currentUser.getUserId());
        billRecord2.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord2);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "修改库存调整单草稿", notes = "修改库存调整单草稿")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/updateInventoryAdjust")
    @Transactional
    public Result updateInventoryAdjust(@RequestBody InventoryAdjustCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        InventoryAdjust inventoryAdjust = criteria.getInventoryAdjust();
        BillRecord billRecord;

        billRecord = billRecordService.findByBillNoAndType(inventoryAdjust.getBillNo(),43);

        billRecord.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord.setModifyUserId(currentUser.getUserId());
        billRecord.setModifyUserName(currentUser.getUserName());
        inventoryAdjustDetailService.deleteByBillNo(inventoryAdjust.getBillNo());
        for(int j=0;j<criteria.getAdjustDetails().size();j++){
            InventoryAdjustDetail inventoryAdjustDetail = criteria.getAdjustDetails().get(j);
            inventoryAdjustDetail.setAdjustDetailId(null);
            inventoryAdjustDetail.setBillNo(inventoryAdjust.getBillNo());
            inventoryAdjustDetail.setDetailNo(inventoryAdjust.getBillNo()+"-"+(j+1));
            inventoryAdjustDetail.setDifferQuantity(inventoryAdjustDetail.getAdjustQuantity()-inventoryAdjustDetail.getQuantity());
            inventoryAdjustDetail.setState(1);
            inventoryAdjustDetail.setCreateTime(DateUtils.getNowDateTimeString());
            inventoryAdjustDetail.setCreateUseId(currentUser.getUserId());
            inventoryAdjustDetail.setCreateUseName(currentUser.getUserName());
            inventoryAdjustDetail.setMemo(inventoryAdjust.getMemo()+"新增或者减少库存");
            inventoryAdjustDetailService.save(inventoryAdjustDetail);
        }
        billRecordService.updateById(billRecord);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "库存调整单草稿提交", notes = "库存调整单草稿提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/commitDraft")
    @Transactional
    public Result commitDraft(@RequestBody InventoryAdjustCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        InventoryAdjust inventoryAdjust = criteria.getInventoryAdjust();
        inventoryAdjustService.removeById(inventoryAdjust.getInventoryAdjustId());
        String tableName = "inventory_adjust";
        Integer nextId = validatorService.getNextId(tableName);
        String billNo = "IA" + "-" + nextId;

        //添加调整单跟踪信息
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(36);//调整新增
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.save(billRecord);

        int caseState = caseMasterService.createCase(billNo, 6, currentUser.getUserId(), inventoryAdjust.getWareId(), inventoryAdjust.getOrganizationId());

        inventoryAdjust.setInventoryAdjustId(null);
        inventoryAdjust.setBillNo(billNo);
        inventoryAdjust.setCreateTime(DateUtils.getNowDateTimeString());
        inventoryAdjust.setUserId(currentUser.getUserId());
        inventoryAdjust.setUserName(currentUser.getUserName());
        inventoryAdjust.setCaseState(caseState);
        inventoryAdjust.setInsertType(criteria.getInsertType());
        inventoryAdjustService.save(inventoryAdjust);

        BillRecord billRecord1 =new BillRecord();
        billRecord1.setBillNo(billNo);
        billRecord1.setRecordType(37);//调整审核
        billRecord1.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord1.setCreateUserId(currentUser.getUserId());
        billRecord1.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord1,currentUser);
        if(caseState==1){
            billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord1.setModifyUserId(currentUser.getUserId());
            billRecord1.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord1);
        }
        //BillRecord billRecord = new BillRecord(billNo, DateUtils.getNowDateTimeString(), currentUser.getUserId(), currentUser.getUserName());
        if (inventoryAdjust.getType().equals(1)){
            //billRecord.setRecordType(BillRecordTypeConstants.UPDATE_INVENTORY_CHECK_CREATE_INVENTORY_ADJUST_DRAFT_TO_OFFICIAL);
            billRecord.setMemo("盘点单库存调整单草稿生成库存调整单");
            billRecordService.updateById(billRecord);
        }else{
            //billRecord.setRecordType(BillRecordTypeConstants.UPDATE_MANUAL_CREATE_INVENTORY_ADJUST_DRAFT_TO_OFFICIAL);
            billRecord.setMemo("手动选择库存调整单草稿生成库存调整单");
            billRecordService.updateById(billRecord);

        }

        for(int j=0;j<criteria.getAdjustDetails().size();j++){
            InventoryAdjustDetail inventoryAdjustDetail = criteria.getAdjustDetails().get(j);
            inventoryAdjustDetail.setAdjustDetailId(null);
            inventoryAdjustDetail.setBillNo(billNo);
            inventoryAdjustDetail.setDetailNo(billNo+"-"+(j+1));
            inventoryAdjustDetail.setDifferQuantity(inventoryAdjustDetail.getAdjustQuantity()-inventoryAdjustDetail.getQuantity());
            inventoryAdjustDetail.setState(1);
            inventoryAdjustDetail.setCreateTime(DateUtils.getNowDateTimeString());
            inventoryAdjustDetail.setCreateUseId(currentUser.getUserId());
            inventoryAdjustDetail.setCreateUseName(currentUser.getUserName());
            inventoryAdjustDetail.setMemo(criteria.getMemo());
            inventoryAdjustDetailService.save(inventoryAdjustDetail);
        }
        BillRecord billRecord2 =billRecordService.findByBillNoAndType(billNo,36);//调整新增
        billRecord2.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord2.setModifyUserId(currentUser.getUserId());
        billRecord2.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord2);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "审核", notes = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/review")
    public Result review(String billNo, Integer reviewResult,Integer caseDetailId,String memo, @ApiIgnore @User CurrentUser currentUser) {
        InventoryAdjust inventoryAdjust = inventoryAdjustService.findBy("bill_no", billNo);
        //-1不通过   0-流转中  1-通过  2-初始化
        Integer lastReviewResult = caseMasterService.review(caseDetailId,currentUser.getUserId(),reviewResult,memo);


        if (lastReviewResult == -1) {
            inventoryAdjust.setCaseState(-1);
            inventoryAdjustService.updateById(inventoryAdjust);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,37);//调整审核
            billRecord.setResult("退回");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 0) {
            inventoryAdjust.setCaseState(0);
            inventoryAdjustService.updateById(inventoryAdjust);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,37);//调整审核
            billRecord.setResult("流转");
            billRecordService.updateById(billRecord);
        }else if (lastReviewResult == 2) {
            inventoryAdjust.setCaseState(2);
            inventoryAdjustService.updateById(inventoryAdjust);
        } else if (lastReviewResult == 1) {
            inventoryAdjust.setCaseState(1);
            inventoryAdjustService.updateById(inventoryAdjust);

            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,37);//调整审核
            billRecord.setResult("通过");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "重新发起审核", notes = "重新发起审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/reReview")
    public Result reReview(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        InventoryAdjust inventoryAdjust = inventoryAdjustService.findBy("bill_no", billNo);

        //初始化状态 2
        inventoryAdjust.setCaseState(2);
        inventoryAdjustService.updateById(inventoryAdjust);
        caseMasterService.createCase(billNo, 2, currentUser.getUserId(), inventoryAdjust.getWareId(),inventoryAdjust.getOrganizationId());

        return ResultGenerator.genSuccessResult();
    }



}
